<template>
	<el-main>
		<el-card class="box-card" shadow="never">
			<div class="search-box">
				<el-form ref="form" :model="searchForm" label-width="80px">
					<el-form-item label="订单类型" style="margin-bottom: 10px;">
						<el-button-group>
							<el-button :type="buttonType('type', 0)" @click="checkOrder(0)">全部
							</el-button>
							<el-button :type="buttonType('type', 1)" @click="checkOrder(1)">普通订单
							</el-button>
							<el-button :type="buttonType('type', 2)" @click="checkOrder(2)">拼团订单
							</el-button>
							<el-button :type="buttonType('type', 3)" @click="checkOrder(3)">秒杀订单
							</el-button>
							<el-button :type="buttonType('type', 4)" @click="checkOrder(4)">砍价订单
							</el-button>
							<el-button :type="buttonType('type', 5)" @click="checkOrder(5)">删除的订单
							</el-button>
						</el-button-group>
					</el-form-item>
					<el-form-item label="订单状态" style="margin-bottom: 10px;">
						<el-button-group>
							<el-button :type="buttonType('status', 0)" @click="checkOrderStatus(0)">全部
							</el-button>
							<el-button :type="buttonType('status', 2)" @click="checkOrderStatus(2)">
								待支付
							</el-button>
							<el-button :type="buttonType('status', 3)" @click="checkOrderStatus(3)">
								<el-badge :value="unDelivery" class="item" type="danger" v-if="unDelivery > 0">待发货
								</el-badge>
								<span v-else>待发货</span>
							</el-button>
							<el-button :type="buttonType('status', 4)" @click="checkOrderStatus(4)">
								待收货
							</el-button>
							<el-button :type="buttonType('status', 5)" @click="checkOrderStatus(5)">
								部分发货
							</el-button>
							<el-button :type="buttonType('status', 6)" @click="checkOrderStatus(6)">
								交易完成
							</el-button>
							<el-button :type="buttonType('status', 7)" @click="checkOrderStatus(7)">
								已取消
							</el-button>
							<el-button :type="buttonType('status', 8)" @click="checkOrderStatus(8)">
								已关闭
							</el-button>
							<el-button :type="buttonType('status', 9)" @click="checkOrderStatus(9)">
								库存不足
							</el-button>
						</el-button-group>
					</el-form-item>
					<el-form-item label="支付状态" style="margin-bottom: 10px;">
						<el-button-group>
							<el-button :type="buttonType('pay_status', 0)" @click="checkPayStatus(0)">
								全部
							</el-button>
							<el-button :type="buttonType('pay_status', 1)" @click="checkPayStatus(1)">
								待支付
							</el-button>
							<el-button :type="buttonType('pay_status', 2)" @click="checkPayStatus(2)">
								已支付
							</el-button>
							<el-button :type="buttonType('pay_status', 3)" @click="checkPayStatus(3)">
								已退款
							</el-button>
							<el-button :type="buttonType('pay_status', 4)" @click="checkPayStatus(4)">
								部分退款
							</el-button>
							<el-button :type="buttonType('pay_status', 5)" @click="checkPayStatus(5)">
								部分支付
							</el-button>
							<el-button :type="buttonType('pay_status', 6)" @click="checkPayStatus(6)">
								支付异常
							</el-button>
						</el-button-group>
					</el-form-item>
				</el-form>
				<el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="80px">
					<el-form-item label="支付单号">
						<el-input v-model="searchForm.order_no" placeholder="支付单号" style="width: 300px"
						></el-input>
					</el-form-item>
					<el-form-item label="下单时间">
						<el-date-picker
							v-model="searchForm.create_time"
							type="daterange"
							value-format="YYYY-MM-DD"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="支付方式">
						<el-select v-model="searchForm.pay_way" placeholder="支付方式" style="width: 300px" clearable>
							<el-option label="微信" value="1"></el-option>
							<el-option label="支付宝" value="2"></el-option>
							<el-option label="余额" value="3"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="下单人ID">
						<el-input v-model="searchForm.user_id" placeholder="下单人id" style="width: 300px" type="number" clearable></el-input>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="search" icon="el-icon-search">查询</el-button>
						<el-button type="primary" @click="exportOrder" icon="el-icon-position">导出</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div style="width:100%;height:0;border-bottom:#E4E7ED 1px dashed;margin-bottom: 10px"></div>
			<el-table
				v-loading="tableLoading"
				:data="tableData"
				:row-style="{ height: '57px'}"
				style="width: 100%;font-size: 12px">
				<el-table-column
					label="订单号"
					width="200px">
					<template #default="scope">
						<p>
							{{ scope.row.order_no }}
							<el-icon :size="16" @click="copyText(scope.row.order_no)" style="cursor: pointer">
								<component :is="copyIcon"/>
							</el-icon>
						</p>
						<p>[{{ scope.row.order_txt }}]</p>
						<p>
							<el-tag v-if="scope.row.is_del == 2" size="mini" type="warning">后台已删除</el-tag>
							<el-tag v-if="scope.row.user_del == 2" size="mini" type="danger">用户已删除</el-tag>
						</p>
					</template>
				</el-table-column>
				<el-table-column
					label="购买人"
					width="150px">
					<template #default="scope">
						<p>{{ scope.row.user.nickname }}</p>
						<p>
							ID: {{ scope.row.user.id }}
							<el-icon :size="16" @click="copyText(scope.row.user.id)" style="cursor: pointer">
								<component :is="copyIcon"/>
							</el-icon>
						</p>
					</template>
				</el-table-column>
				<el-table-column
					label="商品信息"
					width="350px">
					<template #default="scope">
						<div v-for="item in scope.row.detail" :key="item.id">
							<div class="goods-info">
								<div class="goods-img">
									<img :src="item.logo" style="height: 36px;width: 36px">
								</div>
								<div class="goods-name" v-if="item.rule != 0">
									{{ item.goods_name }} | {{ item.rule.split('※').join(',') }}
								</div>
								<div class="goods-name" v-else>
									{{ item.goods_name }}
								</div>
							</div>
							<div class="goods-price">
								￥{{ item.price }} × {{ item.cart_num }}
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column
					prop="pay_price"
					label="实际支付">
				</el-table-column>
				<el-table-column
					prop="pay_status"
					label="支付状态">
				</el-table-column>
				<el-table-column
					label="订单状态"
					width="100px">
					<template #default="scope">
						<p>{{ scope.row.status_txt }}</p>
						<el-tag v-if="scope.row.refund_status == 1 && scope.row.refund_type == 1" size="mini"
								type="danger">退款中
						</el-tag>
						<el-tag v-if="scope.row.refund_status == 1 && scope.row.refund_type == 2" size="mini"
								type="danger">退货退款中
						</el-tag>
						<el-tag v-if="scope.row.type == 2 && scope.row.groupon_status == 1" type="danger" size="mini">
							拼团中
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column
					prop="pay_way"
					label="支付方式">
				</el-table-column>
				<el-table-column
					prop="pay_time"
					label="支付时间"
					width="160px">
				</el-table-column>
				<el-table-column
					prop="create_time"
					label="下单时间"
					width="160px">
				</el-table-column>
				<el-table-column
					label="操作"
					fixed="right"
					width="150px">
					<template #default="scope">
						<div v-if="scope.row.type != 2">
							<el-button @click="handleDeliver(scope.row)" type="text"
									   v-if="scope.row.status == 3 || scope.row.status == 5 " size="small">发货
							</el-button>

							<el-dropdown @command="handleMore($event, scope.row)" style="margin-top: 6px">
								<span class="el-dropdown-link" style="font-size: 12px;color: var(--el-color-primary);">
								更多 <i class="el-icon-arrow-down el-icon--right"></i>
								</span>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item command="detail">订单详情</el-dropdown-item>
										<el-dropdown-item command="log">状态记录</el-dropdown-item>
										<el-dropdown-item command="complete"
														  v-if="scope.row.status == 3 || scope.row.status == 4 || scope.row.status == 5">
											完成订单
										</el-dropdown-item>
										<el-dropdown-item command="del">删除订单</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
						<div v-else>
							<el-button @click="handleDeliver(scope.row)" type="text"
									   v-if="(scope.row.status == 3 || scope.row.status == 5) && scope.row.groupon_status == 2" size="small">
								发货
							</el-button>
							<el-dropdown @command="handleMore($event, scope.row)" style="margin-top: 6px">
								<span class="el-dropdown-link" style="font-size: 12px;color: var(--el-color-primary);">
								更多 <i class="el-icon-arrow-down el-icon--right"></i>
								</span>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item command="detail">订单详情</el-dropdown-item>
										<el-dropdown-item command="log">状态记录</el-dropdown-item>
										<el-dropdown-item command="complete"
														  v-if="scope.row.status == 3 || scope.row.status == 4 || scope.row.status == 5">
											完成订单
										</el-dropdown-item>
										<el-dropdown-item command="del">删除订单</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<Pages :form="searchForm" :page-obj="page" @pageChange="pageChangeHandle" @pageJump="getList"></Pages>

		</el-card>
	</el-main>

	<el-dialog
		title="订单详情"
		v-model="orderVisible"
		width="1000px">
		<el-descriptions title="订单信息">
			<el-descriptions-item label="订单ID">{{ orderDetail.info.order_no }}</el-descriptions-item>
			<el-descriptions-item label="订单状态">
				<el-tag size="small">{{ orderDetail.status[orderDetail.info.status] }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="购买数量">{{ orderDetail.info.total_num }}</el-descriptions-item>
			<el-descriptions-item label="商品总价">{{ orderDetail.info.order_price }}</el-descriptions-item>
			<el-descriptions-item label="实际支付">
				<el-tag size="small" type="danger">{{ orderDetail.info.pay_price }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="支付邮费">{{ orderDetail.info.pay_postage }}</el-descriptions-item>
			<el-descriptions-item label="退款金额">-{{ orderDetail.info.refunded_price }}</el-descriptions-item>
			<el-descriptions-item label="会员优惠">-{{ orderDetail.info.vip_discount }}</el-descriptions-item>
			<el-descriptions-item label="优惠券金额">-{{ orderDetail.info.coupon_amount }}</el-descriptions-item>
			<el-descriptions-item label="下单时间">{{ orderDetail.info.create_time }}</el-descriptions-item>
			<el-descriptions-item label="发货时间">{{ orderDetail.info.delivery_time }}</el-descriptions-item>
			<el-descriptions-item label="支付时间">{{ orderDetail.info.pay_time }}</el-descriptions-item>
			<el-descriptions-item label="支付方式">
				<el-tag size="small">{{ orderDetail.payWay[orderDetail.info.pay_way] }}</el-tag>
			</el-descriptions-item>
			<el-descriptions-item label="三方单号">{{ orderDetail.info.third_code }}</el-descriptions-item>
			<el-descriptions-item label="三方信息"><span style="cursor: pointer;color:#409EFF;" @click="thirdDetail(orderDetail.info)">查看</span></el-descriptions-item>
			<el-descriptions-item label="买家备注">{{ orderDetail.info.remark }}</el-descriptions-item>
		</el-descriptions>
		<el-descriptions title="收件信息">
			<el-descriptions-item label="用户昵称">{{ orderDetail.info.user.nickname }}</el-descriptions-item>
			<el-descriptions-item label="收货人">{{ orderDetail.info.address.user_name }}</el-descriptions-item>
			<el-descriptions-item label="联系电话">{{ orderDetail.info.address.phone}}</el-descriptions-item>
			<el-descriptions-item label="收货地址">{{ orderDetail.info.address.province }}{{ orderDetail.info.address.city }}{{ orderDetail.info.address.county }}{{ orderDetail.info.address.detail }}</el-descriptions-item>
		</el-descriptions>
		<el-descriptions title="物流信息">
			<el-descriptions-item label="快递公司">{{ orderDetail.info.delivery_name }}</el-descriptions-item>
			<el-descriptions-item label="单号">{{ orderDetail.info.delivery_no }}
				<el-tag @click="showExpress" style="cursor: pointer;margin-left: 10px;" size="small">物流详情</el-tag>
			</el-descriptions-item>
		</el-descriptions>
	</el-dialog>

	<el-dialog
		title="物流详情"
		v-model="expressVisible"
		width="800px">
		<el-timeline v-if="orderDetail.detail.result.list.length > 0">
			<el-timeline-item
				v-for="(activity, index) in orderDetail.detail.result.list"
				:key="index"
				:timestamp="activity.time">
				{{ activity.status }}
			</el-timeline-item>
		</el-timeline>
		<el-empty description="暂无数据" v-else></el-empty>
	</el-dialog>

	<el-dialog
		title="状态记录"
		v-model="orderLineVisible"
		width="600px">
		<el-timeline>
			<el-timeline-item
				v-for="(item, index) in orderLog"
				:key="index"
				:timestamp="item.create_time">
				{{ item.msg }}
			</el-timeline-item>
		</el-timeline>
	</el-dialog>

	<el-dialog
		title="订单发货"
		v-model="deliverVisible"
		width="800px">
		<el-form ref="form" :model="deliverForm" label-width="80px">
			<el-form-item label="选择类型">
				<el-radio label="1" v-model="deliverForm.type" v-if="goodsType == 1">快递</el-radio>
				<el-radio label="2" v-model="deliverForm.type">无需发货</el-radio>
			</el-form-item>
			<el-form-item label="快递公司" v-if="deliverForm.type == 1">
				<el-select v-model="deliverForm.delivery_name" placeholder="请选择快递公司" style="width: 100%">
					<el-option :label="item.name" :value="item.name" v-for="item in express" :key="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="快递单号" v-if="deliverForm.type == 1">
				<el-input v-model="deliverForm.delivery_no"></el-input>
			</el-form-item>
			<el-form-item label="分单发货" v-if="canSplit && deliverForm.type == 1">
				<el-switch
					v-model="deliverForm.split_order">
				</el-switch>
			</el-form-item>
			<el-form-item label="发货商品" v-if="deliverForm.split_order && deliverForm.type == 1">
				<el-table
					:data="sendGoods"
					@selection-change="handleSelectionChange"
					style="width: 100%">
					<el-table-column
						type="selection"
						width="55">
					</el-table-column>
					<el-table-column
						label="商品图"
						width="80">
						<template #default="scope">
							<img :src="scope.row.logo" style="width: 36px;height: 36px"/>
						</template>
					</el-table-column>
					<el-table-column
						show-overflow-tooltip
						prop="goods_name"
						label="商品名称">
					</el-table-column>
					<el-table-column
						label="规格">
						<template #default="scope">
							<span v-if="scope.row.rule != ''">{{ scope.row.rule.replace('※', ',') }}</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="price"
						width="100"
						label="价格">
					</el-table-column>
					<el-table-column
						prop="cart_num"
						width="80"
						label="数量">
					</el-table-column>
					<el-table-column
						label="发货数量">
						<template #default="scope">
							<el-input v-model="scope.row.send_num" type="number"></el-input>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="doExpress" :loading="loading">立即提交</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>

	<el-dialog
		title="三方返回信息"
		v-model="thirdVisible"
		width="1000px">
		<el-empty description="暂无" v-if="third_return == ''"></el-empty>
		<el-descriptions title="" direction="vertical" :column="4" border v-else>
			<el-descriptions-item :label="key" v-for="(item,key) in third_return" :key="key">{{ item }}</el-descriptions-item>
		</el-descriptions>
	</el-dialog>
</template>

<script>
import Pages from "@/components/pages/index.vue";
import * as XLSX from "xlsx";
export default {
	components: {Pages},
	data() {
		return {
			searchForm: {
				type: 0,
				status: 0,
				pay_status: 0,
				order_no: '',
				pay_way: '',
				user_id: '',
				create_time: '',
				excel_page: 1,
				step: 1,
				page: 1,
				limit: 10
			},
			goodsType: 1,
			deliverForm: {
				order_id: 0,
				type: '1',
				delivery_name: '',
				delivery_code: '',
				delivery_no: '',
				split_order: false,
				order_detail_ids: []
			},
			express: [],
			page: {
				total: 0
			},
			thirdVisible: false,
			tableLoading: false,
			loading: false,
			tableData: [],
			orderVisible: false,
			expressVisible: false,
			orderLineVisible: false,
			deliverVisible: false,
			orderLog: [],
			orderDetail: {
				info: {
					user: {},
					address: {}
				},
				status: {},
				payWay: {},
				detail: {
					result: {
						list: []
					}
				},
				refund: {},
				refund_amount: {}
			},
			unDelivery: 0,
			third_return: {},
			canSplit: false, // 是否可以分单发货
			sendGoods: [], // 发货商品
			copyIcon: 'el-icon-CopyDocument'
		}
	},
	mounted() {
		this.getList()
	},
	methods: {
		// 获取列表
		async getList() {
			let res = await this.$API.order.list.get(this.searchForm)
			this.tableData = res.data.data
			this.page.total = res.data.total
			this.unDelivery = res.data.unDelivery
		},
		// 选择订单
		checkOrder(type) {
			this.searchForm.type = type
			this.searchForm.page = 1
			this.getList()
		},
		// 选择订单状态
		checkOrderStatus(status) {
			this.searchForm.status = status
			this.getList()
		},
		// 支付状态
		checkPayStatus(status) {
			this.searchForm.pay_status = status
			this.getList()
		},
		// 查询
		search() {
			this.getList()
		},
		pageChangeHandle(page) {
			this.searchForm.page = page
			this.getList()
		},
		// 发货
		async handleDeliver(row) {
			this.deliverForm.order_id = row.id
			this.deliverVisible = true
			if (row.detail.length > 1) {
				this.canSplit = true
			} else {
				this.canSplit = false
			}
			this.sendGoods = []
			row.detail.forEach(item => {
				this.sendGoods.push({
					id: item.id,
					logo: item.logo,
					goods_name: item.goods_name,
					rule: item.rule,
					price: item.price,
					cart_num: item.cart_num,
					send_num: item.cart_num
				})
			})

			let res = await this.$API.order.express.get({id: row.id})
			if (res.code == 0) {
				this.express = res.data.express
				this.goodsType = res.data.goods_type

				if (this.goodsType == 2) {
					this.deliverForm.type = '2'
				}
			}
		},
		// 更多的方法
		handleMore(event, row) {
			if (event == 'detail') {
				this.orderVisible = true
				this.getOrderDetail(row.id)
			} else if (event == 'log') {
				this.orderLineVisible = true
				this.getOrderLog(row.id)
			} else if (event == 'complete') {
				this.completeOrder(row.id)
			} else if (event == 'del') {
				this.delOrder(row.id)
			}
		},
		// 订单详情
		async getOrderDetail(id) {
			let res = await this.$API.order.detail.get({id: id})
			this.orderDetail = res.data
			// 设置默认数据
			if (!this.orderDetail.detail || this.orderDetail.detail.length == 0) {
				this.orderDetail.detail = {
					result: {
						list: []
					}
				}
			}
		},
		// 物流详情
		showExpress() {
			this.expressVisible = true
		},
		// 订单记录
		async getOrderLog(id) {
			let res = await this.$API.order.log.get({id: id})
			this.orderLog = res.data
		},
		// 物流发货
		async doExpress() {
			this.loading = true
			this.express.forEach(item => {
				if (item.name == this.deliverForm.delivery_name) {
					this.deliverForm.delivery_code = item.code
				}
			})
			let res = await this.$API.order.doExpress.post(this.deliverForm)
			this.loading = false
			if (res.code == 0) {
				this.deliverVisible = false
				this.deliverForm = this.$options.data().deliverForm
				this.$message.success(res.msg)
				this.getList()
			} else {
				this.$message.error(res.msg)
			}
		},
		// 完成订单
		completeOrder(id) {
			this.$confirm('确定完成该订单吗？订单状态不可逆，一旦标记为完成，则无法继续操作该订单，请谨慎操作！', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				let res = await this.$API.order.complete.get({id: id})
				if (res.code == 0) {
					this.getList()
					this.$message.success(res.msg)
				} else {
					this.$message.error(res.msg)
				}
			}).catch(() => {
			});
		},
		// 删除订单
		delOrder(id) {
			this.$confirm('确定删除该订单吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				let res = await this.$API.order.del.get({id: id})
				if (res.code == 0) {
					this.getList()
					this.$message.success(res.msg)
				} else {
					this.$message.error(res.msg)
				}
			}).catch(() => {
			});
		},
		// 导出订单
		async exportOrder() {
			let res = await this.$API.order.export.post(this.searchForm)
			if (res.code == -100) {
				this.searchForm.step = 2
				for (let i = 1; i <= res.data; i++) {
					this.searchForm.excel_page = i;
					let res2 = await this.$API.order.export.post(this.searchForm)
					this.doExport(res2, i);
				}
			} else if (res.code == 0) {
				this.doExport(res, '1');
			}
		},
		doExport(res, name) {
			const wb = XLSX.utils.book_new();
			let ws = XLSX.utils.aoa_to_sheet(res.data);
			ws['!cols'] = [
				{ wpx: 200 }, { wpx: 100 }, { wpx: 100 }, { wpx: 500 }, { wpx: 500 }, { wpx: 100 },
				{ wpx: 100 }, { wpx: 100 }, { wpx: 100 }, { wpx: 200 }, { wpx: 100 }, { wpx: 200 }, { wpx: 200 },
			]

			XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
			XLSX.writeFile(wb, "订单信息" + Date.now() + "_" + name + ".xlsx");
		},
		// 三方信息详情
		thirdDetail(info) {
			this.thirdVisible = true
			this.third_return = info.return_msg ? JSON.parse(info.return_msg) : ''
		},
		// 选择样式
		buttonType(field, type) {
			if (field == 'type') {
				if (this.searchForm.type == type) {
					return 'primary'
				}
			} else if (field == 'status') {
				if (this.searchForm.status == type) {
					return 'primary'
				}
			} else if (field == 'pay_status') {
				if (this.searchForm.pay_status == type) {
					return 'primary'
				}
			}
		},
		// 选中的商品
		handleSelectionChange(row) {
			this.deliverForm.order_detail_ids = []
			row.forEach(item => {
				this.deliverForm.order_detail_ids.push({
					id: item.id,
					num: item.send_num
				})
			})
		},
		copyText(text) {
			navigator.clipboard.writeText(text).then(() => {
				this.$message.success('复制成功')
			}).catch(error => {
				console.log('错误', error)
				this.$message.error('复制错误')
			});
		}
	}
}
</script>

<style scoped>
.primary {
	color: #FFF;
	background-color: #409EFF;
	border-color: #409EFF;
}

.goods-info {
	width: 100%;
	display: flex;
}

.goods-info .goods-img {
	height: 36px;
	width: 36px;
	margin-top: 6px;
}

.goods-name {
	margin-left: 10px
}

.goods-price {
	color: #F56C6C;
	font-weight: 700;
	padding-left: 36px;
	margin-left: 10px
}

.el-dropdown-link {
	cursor: pointer;
	color: #409EFF;
}

.el-icon-arrow-down {
	font-size: 12px;
}

.el-badge__content--danger {
	top: -10px !important
}
.el-button--small {
	padding: 0 !important;
}
</style>
